using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Commands.AssignMenusToRole;

public class AssignMenusToRoleCommandHandler : IRequestHandler<AssignMenusToRoleCommand, ApiResult<bool>>
{
  private readonly IUnitOfWork _unitOfWork;
  private readonly ILogger<AssignMenusToRoleCommandHandler> _logger;

  public AssignMenusToRoleCommandHandler(IUnitOfWork unitOfWork, ILogger<AssignMenusToRoleCommandHandler> logger)
  {
    _unitOfWork = unitOfWork;
    _logger = logger;
  }

  public async Task<ApiResult<bool>> Handle(AssignMenusToRoleCommand request, CancellationToken cancellationToken)
  {
    try
    {
      // 获取角色
      var role = await _unitOfWork.RoleRepository.GetRoleWithMenusAsync(request.RoleId);
      if (role == null)
      {
        return ApiResult<bool>.Failure(404, "角色不存在");
      }

      // 获取所有菜单
      var menus = await _unitOfWork.MenuRepository.FindAsync(m => request.MenuIds.Contains(m.Id));
      if (!menus.Any())
      {
        return ApiResult<bool>.Failure(400, "没有有效的菜单ID");
      }

      // 清除现有菜单权限
      role.RoleMenus.Clear();

      // 添加新菜单权限
      foreach (var menu in menus)
      {
        role.RoleMenus.Add(new RoleMenu { Role = role, Menu = menu });
      }

      // 保存更改
      await _unitOfWork.SaveChangesAsync();

      return ApiResult<bool>.Success(true, "菜单权限分配成功");
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, "分配菜单权限时发生错误");
      return ApiResult<bool>.Failure(500, "分配菜单权限时发生错误");
    }
  }
}